from django.shortcuts import render, reverse, redirect
from django.contrib.auth.models import User
from django.contrib.auth import logout, login, authenticate
import random
from blog import settings


def login_view(request):
	tips = ''
	if request.method == "POST":
		username = request.POST.get('username', '')
		password = request.POST.get('password', '')
		remember_me = request.POST.get('remember_me')
		if User.objects.filter(username=username):
			user = authenticate(username=username, password=password)
			if user:
				if user.is_active:
					login(request, user)
					request.session['username']=username
					request.session.set_expiry(0)
					return redirect(reverse('front:index'))
			else:
				tips = '老铁，您的密码有误！'
		else:
			tips = '老铁，用户名不存在！'
	else:
		pass
	return render(request, 'login.html', locals())


def register_view(request):
	if request.method == 'POST':
		username = request.POST.get('username')
		email = request.POST.get('email')
		password1 = request.POST.get('password1')
		password2 = request.POST.get('password2')
		if User.objects.filter(username=username):
			tips = '老铁，该用户名已存在！'
		else:
			if password1 == password2:
				User.objects.create_user(username=username, email=email, password=password1)
				tips='老铁，注册成功，请登录'
				return render(request, 'register.html', locals())
			else:
				tips = '老铁，两次密码不一致，请重新输入！'
	return render(request, 'register.html', locals())


def logout_view(request):
	logout(request)
	return redirect(reverse('user:login'))


def verificationCode_view(request):
	tips=''
	new_password_buton=False
	button='获取验证码'
	if request.method == 'POST':

		username = request.POST.get('username',)
		verificationCode = request.POST.get('verificationCode', )
		new_password = request.POST.get('new_password',)

		if User.objects.filter(username=username):
			user = User.objects.get(username=username)
			new_password_button=True
			button = '确定'
			tips = '老铁，验证码已发送到你的邮箱了！'
			if request.session.get('verificationCode') == verificationCode:

				print(new_password)
				print(user)
				user.set_password(new_password)
				user.save()

				del request.session['verificationCode']
				tips='老铁，密码已经修改了！'
			elif not request.session.get('verificationCode'):

				verificationCode = str(random.randint(1000, 9999))
				request.session['verificationCode'] = verificationCode
				print(verificationCode)
				user.email_user('密码找回', verificationCode)
			else:
				del request.session['verificationCode']
				button='重发验证码'
				tips='老铁，验证码错了'


		else:
			tips = '老铁，没这个用户！'
			return render(request, 'verificationCode.html', locals())

	return render(request, 'verificationCode.html', locals())
